<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Spinatiev Ivan
 * Date: 9/19/12
 * Time: 11:05 AM
 * To change this template use File | Settings | File Templates.
 */

class Db_Cms_PagePagination extends Common {
    protected static $tableName = TAB_PAGE_PAGINATION;
    protected static $dbFields = array(
        'id',
        'pp_page_id',
        'pp_pagination_number',
        'pp_page_title',
        'pp_page_url',
        'pp_head_line',
        'pp_sub_head_line',
        'pp_category_id',
        'pp_photo_id',
        'pp_photo_alt_tag',
        'pp_photo_name',
        'deleted'
    );

    /**
     * @var Db_Cms_PagePagination
     */
    public $objectArray;

    public $id;
    public $pp_page_id;
    public $pp_pagination_number;
    public $pp_page_title;
    public $pp_page_url;
    public $pp_head_line;
    public $pp_sub_head_line;
    public $pp_category_id;
    public $pp_photo_id;
    public $pp_photo_alt_tag;
    public $pp_photo_name;
    public $deleted;

    function __construct($value=NULL, $fieldName=NULL) {
        parent::__construct($value, $fieldName);
    }

	/**
	 * @static
	 * @param $pageId
	 * @return array|bool
	 */
	public static function findAllPaginationsForPage($pageId){
		$sql = "SELECT pp.*,pp.id as pp_id, pc.pc_name, `pcb`.`id` AS `bullet_id`
				FROM ?f pp
				LEFT JOIN ?f pc ON pp.pp_category_id = pc.id AND pc.deleted = 0
				LEFT JOIN ?f pcb ON `pcb`.`pcb_page_pagination_id` = `pp`.`id` AND `pcb`.`deleted` = 0
				WHERE pp.pp_page_id = ? AND pp.deleted = 0
				GROUP BY `pp`.`id`";
		$resultArray = self::find($sql, static::$tableName, TAB_CATEGORIES, TAB_PAGE_CATEGORY_BULLETS, $pageId);
		return !empty($resultArray) ? $resultArray : false;
	}

	/**
	 * @static
	 * @param $pageId
	 * @return mixed
	 */
	public static function getTotalPagePagination($pageId) {
		$sql = "SELECT COUNT(`pp`.`pp_page_id`) FROM ?f AS `pp`
				INNER JOIN ?f AS `p` ON `p`.`id` = `pp`.`pp_page_id`
				WHERE `pp`.`pp_page_id` = ? AND `p`.`p_pagination_type` IN('category', 'poems', 'tags') AND `p`.`deleted` = 0 AND `pp`.`deleted` = 0 ;";
		return self::$DB->selectCell($sql, self::$tableName, TAB_PAGES, $pageId);
	}

	/**
	 * @static
	 * @param $pageId
	 * @param $projectIdentifier
	 * @param bool $sitemap
	 * @return bool|mixed urls from pagination for products
	 */
	public static function getProductsUrlsByPageId($projectIdentifier, $pageId =0, $sitemap = true) {
		if (!$projectIdentifier) {
			return false;
		}
		$where = '';
		if ($pageId) {
			$where = " AND pp.pp_page_id = " . self::$DB->escapeValue($pageId);
		}
		$sql = "SELECT pp.pp_page_url,pp.id,pd.id as product_id FROM ?f pp
				INNER JOIN ?f p ON pp.pp_page_id = p.id AND p.p_pagination_type = 'product' AND p.deleted = 0
				INNER JOIN ?f mp ON p.id = mp.mp_page_id AND mp.deleted = 0
				INNER JOIN ?f m ON mp.mp_menu_id = m.id AND m.deleted = 0
				INNER JOIN ?f pr ON m.m_project_identifier = pr.pr_identifier AND pr.pr_identifier= ? AND pr.deleted = 0
				INNER JOIN ?f cp ON pr.id = cp.cp_project_id
				INNER JOIN ?f prc ON cp.cp_category_id = prc.prc_category_id
				INNER JOIN ?f pd ON pp.pp_pagination_number = pd.id AND prc.prc_product_id = pd.id AND pd.deleted = 0
				WHERE pp.deleted = 0 {$where} GROUP BY p.id,pd.id
		";
		if ($sitemap) {
			return self::$DB->select($sql, self::$tableName, TAB_PAGES, TAB_MENU_PAGES, TAB_MENUS, TAB_PROJECTS, $projectIdentifier, TAB_CATEGORY_PROJECTS, TAB_PRODUCT_CATEGORIES, TAB_PRODUCTS);
		} else {
			$result =  self::$DB->q($sql, self::$tableName, TAB_PAGES, TAB_MENU_PAGES, TAB_MENUS, TAB_PROJECTS, $projectIdentifier, TAB_CATEGORY_PROJECTS, TAB_PRODUCT_CATEGORIES, TAB_PRODUCTS);
			$dataReturn = array();
			while ($data = $result->fetch_object()) {
				$dataReturn[$data->product_id] = $data->pp_page_url;
			}
			return $dataReturn;
		}
	}

	/**
	 * Fetches the paginations together with the bullets. Useful for 'category' and 'poems' pagination types. The function
	 * will query for the bullets for the first pagination and the one specified by $currentPage, if there are no bullets
	 * for the $currentPage, it will link by reference the bullets for the first pagination in the result
	 * @param $pageId The id of the page
	 * @param $currentPage The number of the current page pagination
	 * @param $totalPages The total number of paginations that this page can have
	 * @return array An array containing the paginations and the bullets for the first pagination and the one specified by the $currentPage
	 */
	public static function getPaginationWithBullets($pageId, $currentPage, $totalPages) {
		$resultPaginations = array();
		$sql = "SELECT * FROM ?f p
					INNER JOIN ?f pp ON `p`.`id` = `pp`.`pp_page_id` AND `pp`.`deleted` = 0
					LEFT JOIN ?f pcb ON `pcb`.`pcb_page_pagination_id` = `pp`.`id` AND (`pp`.`pp_pagination_number` = ?d
						OR `pp`.`pp_pagination_number` = ?d )
					WHERE `p`.`id` = ?d AND `pp`.`pp_pagination_number` <= ?d
					ORDER BY `pp`.`pp_pagination_number`, `pcb`.`pcb_number` ASC";
		$raw = self::$DB->q($sql, TAB_PAGES, TAB_PAGE_PAGINATION, TAB_PAGE_CATEGORY_BULLETS, 1, $currentPage,
			$pageId, $totalPages);
		while ($entry = $raw->fetch_assoc()) {
			$paginationNumber = $entry['pp_pagination_number'];
			if (!isset($resultPaginations[$paginationNumber])) {
				$resultPaginations[$paginationNumber] = $entry;
				$resultPaginations[$paginationNumber]['bullets'] = array();
			}
			if ($entry['pcb_number']) {
				$resultPaginations[$paginationNumber]['bullets'][$entry['pcb_number']] = $entry['pcb_content'];
			}
		}
		/* if the pagination for the page the user is currently on does not have any bullets, we'll just use the
		bullets from the first pagination. We link by reference to avoid memory overuse*/
		if ($currentPage && (!isset($resultPaginations[$currentPage]['bullets']) ||
			!count($resultPaginations[$currentPage]['bullets']))) {
			$resultPaginations[$currentPage]['bullets'] =& $resultPaginations[1]['bullets'];
		}
		if (!isset($resultPaginations[$currentPage]['pp_head_line']) && isset($resultPaginations[1]['pp_head_line'])) {
			$resultPaginations[$currentPage]['pp_head_line'] = $resultPaginations[1]['pp_head_line'];
		}
		if (!isset($resultPaginations[$currentPage]['pp_sub_head_line']) && isset($resultPaginations[1]['pp_sub_head_line'])) {
			$resultPaginations[$currentPage]['pp_sub_head_line'] = $resultPaginations[1]['pp_sub_head_line'];
		}
		return $resultPaginations;
	}
}